package com.gzdh.dishrecognition.ui.fragment.report;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSONArray;
import com.blankj.utilcode.util.StringUtils;
import com.dhkj.web.bean.ReserveListDto;
import com.dhkj.web.utils.MyObserverRes;
import com.dhkj.web.utils.RequestUtils;
import com.gzdh.dishrecognition.R;
import com.gzdh.dishrecognition.config.SysConstConfig;
import com.gzdh.dishrecognition.ui.adapter.report.OrderReportAdapter;
import com.gzdh.dishrecognition.ui.dialog.OrderDetailsDialog;
import com.gzdh.dishrecognition.ui.dialog.PopupWindowRight;
import com.gzdh.dishrecognition.util.SystemUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.stream.Collectors;

public class DeviceOrderReportFragment extends Fragment {

    private Context mContext;

    private Activity activity;

    private RecyclerView recyclerView;

    private OrderReportAdapter orderReportAdapter;

    private TextView amountTv;

    private TextView reloadTv;

    private String nameEditText;

    public DeviceOrderReportFragment(Activity activity) {
        this.activity = activity;
    }

    @SuppressLint("MissingInflatedId")
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        View view = inflater.inflate(R.layout.fragment_report_deviceorder, container, false);
        mContext = view.getContext();
        view.findViewById(R.id.sxBut).setOnClickListener(view1 -> {
            PopupWindowRight popupWindowRight = new PopupWindowRight(activity, view1);
            popupWindowRight.setFocusable(true);
            popupWindowRight.showAtLocation(activity.getWindow().getDecorView(), Gravity.RIGHT | Gravity.BOTTOM, 0, 0);
            popupWindowRight.setUserSubmit(this::getOrder);
            nameEditText = popupWindowRight.getName();
        });
        reloadTv = view.findViewById(R.id.reLoadBut);
        reloadTv.setOnClickListener(v -> {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA);
            getOrder(simpleDateFormat.format(new Date()), simpleDateFormat.format(new Date()), nameEditText);
        });
        recyclerView = view.findViewById(R.id.recyclerView);
        amountTv = view.findViewById(R.id.amountTv);
        int size = SysConstConfig.getInstance().getDeviceReportFontSize();
        amountTv.setTextSize(TypedValue.COMPLEX_UNIT_SP, size);
        ((TextView) view.findViewById(R.id.titleOrderTv)).setTextSize(TypedValue.COMPLEX_UNIT_SP, size);
        ((TextView) view.findViewById(R.id.titleNameTv)).setTextSize(TypedValue.COMPLEX_UNIT_SP, size);
        ((TextView) view.findViewById(R.id.titlePriceTv)).setTextSize(TypedValue.COMPLEX_UNIT_SP, size);
        ((TextView) view.findViewById(R.id.titleTimeTv)).setTextSize(TypedValue.COMPLEX_UNIT_SP, size);
        ((TextView) view.findViewById(R.id.titlePayTypeTv)).setTextSize(TypedValue.COMPLEX_UNIT_SP, size);
        ((TextView) view.findViewById(R.id.titleStateTv)).setTextSize(TypedValue.COMPLEX_UNIT_SP, size);
        ((TextView) view.findViewById(R.id.totalTv)).setTextSize(TypedValue.COMPLEX_UNIT_SP, size);
        orderReportAdapter = new OrderReportAdapter(activity);
        LinearLayoutManager layoutManager = new LinearLayoutManager(activity);
        recyclerView.setLayoutManager(layoutManager);
        orderReportAdapter.setUserClick(order -> {
            RequestUtils.getOrderDetails(mContext, order, new MyObserverRes<JSONArray>(mContext) {
                @Override
                public void onSuccess(JSONArray result) {
                    OrderDetailsDialog orderDetailsDialog = new OrderDetailsDialog(mContext);
                    orderDetailsDialog.show();
                    orderDetailsDialog.setJsonArray(result);
                    orderDetailsDialog.setRefundFina(() -> {
                        onResume();
                    });
                    System.out.println(result.toJSONString());
                }

                @Override
                public void onFailure(Throwable e, String errorMsg) {

                }
            });

        });
        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        getOrder(simpleDateFormat.format(new Date()), simpleDateFormat.format(new Date()), nameEditText);

    }

    @Override
    public void onPause() {
        super.onPause();
    }

    public void scrollView(int dx, int dy) {
        recyclerView.smoothScrollBy(dx, dy);
    }

    public void reload() {
        reloadTv.performClick();
    }

    public void getOrder(String startTime, String endTime, String name) {
        RequestUtils.getOrderList(mContext, SystemUtils.getSerialNumber(), startTime, endTime, SysConstConfig.getInstance().getUser(),
        new MyObserverRes<>(mContext) {
            @Override
            public void onSuccess(List<ReserveListDto> result) {
                BigDecimal price = new BigDecimal(0);
                for (ReserveListDto goo : result) {
                    String je = goo.getJe() != null ? goo.getJe() : "0";
                    price = price.add(new BigDecimal(je));
                }
                List<ReserveListDto> list = result;
                if(!StringUtils.isTrimEmpty(name)) {
                    list = result.stream().filter(v -> v.getKehu().contains(name)).collect(Collectors.toList());
                }
                recyclerView.setAdapter(orderReportAdapter);
                orderReportAdapter.setReserveListDtoList(list);
                amountTv.setText(price.setScale(2, RoundingMode.DOWN).toPlainString());
            }

            @Override
            public void onFailure(Throwable e, String errorMsg) {
                if(e != null && e.getCause() != null) {
                    if(e.getCause().toString().contains("java.net.ConnectException")) {
                        errorMsg = "网络异常,请查询脱机记录";
                    }
                }
                Toast.makeText(mContext, errorMsg, Toast.LENGTH_SHORT).show();
            }
        });
    }


}
